package com.lgc.javathread.locktest.synchronizdAndLock.synchronizedTest;

public class Program {
    public static void main(String[] args) {
        /*new Thread(() -> {
            T t = new T();
            for (int i = 0; i < 100; i++) {
                t.m();
                t.m2();
            }
        }).start();*/

        T t2 = new T();
        for (int i = 0; i < 100; i++) {
           new Thread(()->{
               t2.m();
               //t2.m2();
           }).start();
        }
    }
}

class T {
    private int count;
    private static int staticCount;
    private int count2;
    private Object o = new Object();

    //加锁
    public void m() {
        synchronized (o) {//执行下边代码，必须先拿到o的锁
            count--;
            System.out.println(Thread.currentThread().getName() + " count= " + count);
        }
    }

    //或者写成
    public synchronized void m1() { //等同于加了 synchronized(this)
        count--;
        System.out.println(Thread.currentThread().getName() + " count= " + count);
    }

    //不加锁
    public void m2() {
        count2--;
        System.out.println(Thread.currentThread().getName() + " count2= " + count2);
    }

    //或者写成
    public synchronized static void m5() { //等同于加了 synchronized(T.class)
        staticCount--;
        System.out.println(Thread.currentThread().getName() + " staticCount= " + staticCount);
    }
    public static void m6() { //等同于加了 synchronized(T.class)
        synchronized (T.class) {
            staticCount--;
            System.out.println(Thread.currentThread().getName() + " staticCount= " + staticCount);
        }
    }
}
